;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Barcode.DeliveryCode", [])
        .controller("DeliveryCodeCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "UserContextService", "$timeout", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, UserContextService, $timeout) {
            var lodop;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = { onePer: 1 };
            $scope.toolbarConfig = {
                showPrintConf: false
            };
            $scope.dataList = [];
            $scope.detailInfo = {};
            $scope.packList = [];
            $scope.currentMaterial = {};
            $scope.markInfo = {};
            $scope.tempSet = {
                qrCodeSize: 85,
                printMainCode: true,
            };
            $scope.tableConfig = {
                scrollWidth: 720,
                tableCol: [
                    {
                        type: "",
                        name: "打印标志",
                        dataField: "stateName",
                        width: 90
                    },
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 120
                    },
                    {
                        type: "",
                        name: "数量",
                        dataField: "qty",
                        width: 80
                    },
                    {
                        type: "",
                        name: "未打数量",
                        dataField: "restAmount",
                        width: 100
                    },
                    {
                        type: "",
                        name: "仓库",
                        dataField: "outLocation",
                        width: 80
                    },
                    {
                        type: "",
                        name: "行号",
                        dataField: "rowNo",
                        width: 90
                    }
                ]
            };

            var btnPermissionCode = {
                packageCodePrint: window.ActionCode.packageCodePrint
            };

            $scope.btnPermission = {
                packageCodePrint: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getDataList() {
                var service = "device";
                var reqUrl = "/warehouseInbound/insitructionDetail";
                ybHttp.Get(service, reqUrl, $scope.condition).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo = {};
                    $scope.markInfo.cueRow = null;
                    if (!resp.value) {
                        return;
                    }
                    angular.forEach(resp.value, function (item) {
                        item.isChecked = false;
                        item.stateName = $filter('printState')(item.printState);
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        item.qty = item.amount;
                        item.billNo = item.businessOrder;
                        item.restAmount = item.amount - item.printNum;
                    });
                    $scope.dataList = resp.value;
                    $scope.markInfo.allCheckedMaterial = false;
                });
            }

            $scope.countPack = function () {
                $scope.detailInfo.packNum = parseInt($scope.detailInfo.packNum);
                if ($scope.detailInfo.totalQty > $scope.currentMaterial.restAmount) {
                    $scope.detailInfo.totalQty = $scope.currentMaterial.restAmount;
                }
                setEachPack();
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.setPackNum = function () {
                $scope.detailInfo.packNum = parseInt($scope.detailInfo.packNum);
                setEachPack();
            };
            function setEachPack() {
                $scope.packList = [];
                var eachPackNum = Math.floor($scope.detailInfo.totalQty / $scope.detailInfo.packNum);
                for (var i = 0; i < $scope.detailInfo.packNum; i++) {
                    var objData = {
                        currentQty: eachPackNum,
                        vinid: ''
                    };
                    if (i == $scope.detailInfo.packNum - 1) {
                        objData.currentQty = Number((objData.currentQty + $scope.detailInfo.totalQty % $scope.detailInfo.packNum).toFixed(3));
                        $scope.packList.push(objData);
                    } else {
                        $scope.packList.push(objData);
                    }
                }
            }

            $scope.selectRow = function (index) {
                if ($scope.dataList[index].printState == 2) {
                    ybWidget.ShowToaster('error', '请选择未完成的零件打印');
                    return;
                }
                $scope.markInfo.cueRow = index;
                $scope.currentMaterial = $scope.dataList[index];
                $scope.detailInfo.totalQty = angular.copy($scope.currentMaterial.restAmount);
                $scope.detailInfo.packNum = 1;
                $scope.packList = [{currentQty: $scope.currentMaterial.restAmount, vinid: ''}];
            };

            $scope.printTicket = function (type) {
                if ($scope.packList.length == 0) {
                    ybWidget.ShowMessage('没有可打印的条码');
                    return;
                }
                var amount = 0;
                angular.forEach($scope.packList, function (item) {
                    amount = Number((amount + parseFloat(item.currentQty)).toFixed(3));
                    item.barcodeDesc = $scope.detailInfo.barcodeDesc;
                    item.model = $scope.detailInfo.model;
                    item.orawyd = $scope.detailInfo.orawyd;
                });
                if (amount > $scope.detailInfo.totalQty) {
                    ybWidget.ShowMessage('每个包数量总和不得超过最大数量');
                    return;
                }
                var param = {
                    billNo: $scope.currentMaterial.billNo,
                    materialsNo: $scope.currentMaterial.materialsNo,
                    materialsDes: $scope.currentMaterial.materialsDes,
                    totalQty: amount,
                    detailList: $scope.packList,
                    rowNo: $scope.currentMaterial.rowNo
                };
                ybHttp.Post('device', '/barcode/singlePrint', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    startPrint(type, resp.value, false);
                });
            };

            $scope.printList = [];
            async function startPrint(type, printListArr, isBatch) {
                if (!$scope.tempSet.printMainCode) {
                    for (var i = 0; i < printListArr.length; i++) {
                        if (printListArr[i].barcodeFlag === 0) {
                            printListArr.splice(i, 1);

                            if (!isBatch) { // 非批量打印，只有一个总条码，找到 即 退出for循环
                                break;
                            }
                        }
                    }
                }

                $scope.printList = type === "preview" && printType !== 1 ? printListArr : UserContextService.ListGroup(printListArr, 20);

                var printType = $scope.tempSet.printType;
                lodop = UserContextService.GetLodop();
                if (!lodop) {
                    return;
                }

                if (!await UserContextService.InitPrinter(lodop, true, printType)) {
                    return;
                }

                setTimeout(function () {
                    UserContextService.ListPrint($scope.printList, lodop, printType, type === "preview");

                    getDataList();
                    $scope.printList = [];
                    $scope.packList = [];
                }, 300)
            }

            $scope.search = function () {
                localStorage.setItem($scope.storageKey, JSON.stringify($scope.condition));
                getDataList();
            };

            $scope.selectSingle = function (item, list, type, e) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            $scope.batchPrint = function () {
                let selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的零件');
                    return;
                }
                var reqParam = [];
                angular.forEach(selectedDatas, function (item) {
                    if (item.amount > item.printNum) {
                        var obj = {};
                        obj.materialsNo = item.materialNo;
                        obj.materialsDes = item.materialName;
                        obj.totalQty = item.amount - item.printNum;
                        obj.billNo = item.billNo;
                        obj.rowNo = item.rowNo;
                        reqParam.push(obj);
                    }
                    item.isChecked = false;
                });
                if (reqParam.length === 0) {
                    ybWidget.ShowMessage('没有可打印的零件');
                    $scope.markInfo.allCheckedMaterial = false;
                    return;
                }

                var service = "device";
                var reqUrl = "/barcode/batchPrintForSelectWithOne2One";
                ybHttp.Post(service, reqUrl, { one2one: $scope.condition.onePer, prints: reqParam }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp);
                        return;
                    }
                    startPrint('preview', resp.value, true);
                });
            };

            $scope.toolbarConfig = {};
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };
            $scope.reset = function () {
                $scope.condition = { onePer: 1 };
            };

            $scope.selectSupplier = function () {
                var param = {
                    name: "供货商",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.condition.supplierName = data.companyName;
                    $scope.condition.supplierIdSearch = data.id;
                })
            };

            $scope.clearSupplier = function () {
                $scope.condition.supplierName = "";
                $scope.condition.supplierIdSearch = "";
            };


            (function () {
                $scope.storageKey = $state.current.name;
				UserContextService.LocalCache($scope.storageKey, $scope.condition);
                
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);